﻿using JamesZhao.Engine.GameObjects;
using JamesZhao.Engine.Graphics;
using JamesZhao.Engine.Graphics.Effects;
using JamesZhao.Engine.Graphics.Geometry;
using JamesZhao.Engine.Graphics.Visuals;

namespace JamesZhao.Engine.GameComponents
{
    public class MeshComponent : GameComponent
    {
        private readonly MeshDrawable _meshDrawable;
        private Material _material;
        private MeshData _meshData;

        public MeshComponent(GameObject owner) : base(owner)
        {
            _meshDrawable = new MeshDrawable();
        }

        public MeshData Mesh
        {
            get { return _meshData; }
            set
            {
                _meshData = value;
                if (_meshData != null)
                {
                    var meshBuffer =
                        new GeometryBuffer(Engine.GraphicsManager.MainViewport.Device);
                    meshBuffer.InitializeFrom(_meshData);
                    _meshDrawable.GeometryBuffer = meshBuffer;
                    Owner.Engine.GraphicsManager.VisualsList.AttachDrawable(_meshDrawable);
                }
            }
        }

        public Material Material
        {
            get { return _material; }
            set
            {
                if (value != null)
                {
                    _material = value;
                    _meshDrawable.Material = _material;
                }
            }
        }

        public override void OnOwnerChanged()
        {
        }

        public override void Update()
        {
            base.Update();
            if (_meshDrawable != null)
            {
                _meshDrawable.LocalToWorldMatrix = Transform.LocalToWorldMatrix;
            }
        }
    }
}